// pages/scoreMall/scoreMall.js
const productService = require('../../../../api/productService.js')
const storeService = require('../../../../api/storeService.js')
const bannerService = require('../../../../api/bannerService.js')
const memberService = require('../../../../api/memberService.js')
const util = require('../../../../utils/utils.js')

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    banners: [],
    goodsList: [],
    member: {},
    score: 0,
    storeName: '',
    storeId: '',
    phone: false
  },
  // banner跳转
  bannerJumping: function (e) {
    const that = this
    let bannerId = e.currentTarget.dataset.id
    const bannerList = that.data.banners
    let advertisementInfo = null
    bannerList.forEach(item => {
      if (item.id === bannerId) {
        advertisementInfo = item
      }
    });
    console.log(advertisementInfo)
    that.toAdPage(advertisementInfo, 'banner')
  },
  // 前往广告页
  toAdPage: function (pageInfo, pageType) {
    const that = this
    if (pageInfo.linkType === 'APP') {
      // 应用
      // 判断跳转模块
      if (pageInfo.appReturnType === 'MIAOSHA') {
        wx.navigateTo({
          url: '../../activity/seckill/seckill'
        })
      } else if (pageInfo.appReturnType === "RECHARGE") {
        wx.navigateTo({
          url: '../../myCard/recharge/recharge'
        })
      } else if (pageInfo.appReturnType === "MEAL") {
        //  餐饮
      } else if (pageInfo.appReturnType === "RECEIVECOUPON") {
        // 领券中心
        wx.navigateTo({
          url: '../../coupon/couponCenter/couponCenter'
        })
      } else if (pageInfo.appReturnType === "ADVANCE_SELL_PRODUCT") {
        // 预售商品
        wx.navigateTo({
          url: '../../activity/advanceSell/advanceSell'
        })
      } else if (pageInfo.appReturnType === "TEAM_BUYING") {
        // 团购
        wx.navigateTo({
          url: '../../fightGroup/fightGroup/fightGroup'
        })
      } else if (pageInfo.appReturnType === "SCOREMALL") {
        // 积分商场
        wx.navigateTo({
          url: '../../score/scoreMall/scoreMall'
        })
      } else if (pageInfo.appReturnType === "INVITE_MEMBER") {
        // 邀请好友
        wx.navigateTo({
          url: '../../invite/invite'
        })
      } else if (pageInfo.appReturnType === "MEMBER_CARD") {
        // 会员卡
        wx.navigateTo({
          url: '../../myCard/memberCard/memberCard'
        })
      } else if (pageInfo.appReturnType === "MY_COUPON") {
        // 我的优惠券
        wx.navigateTo({
          url: '../../coupon/myCoupon/myCoupon'
        })
      } else if (pageInfo.appReturnType === "NEWMBR") {
        // 新用户专享
        wx.navigateTo({
          url: '../../activity/newmbrActivity/newmbrActivity'
        })
      }
    } else if (pageInfo.linkType === 'GRADPRODUCT') {
      // 秒杀商品
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.productId + '&storeId=' + app.globalData.storeInfo.id + '&type=secondkill'
      })
    } else if (pageInfo.linkType === 'PRODUCT') {
      // 商品 
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.productId + '&storeId=' + app.globalData.storeInfo.id + '&type=normal'
      })
    } else if (pageInfo.linkType === 'TEAMPRODUCT') {
      // 拼团商品 
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.teamActivityId + '&storeId=' + app.globalData.storeInfo.id + '&type=group'
      })
    } else if (pageInfo.linkType === 'COUPONACTIVITYDETAILS') {
      if (app.globalData.userInfo) {
        if (app.globalData.userInfo.member) {
          wx.navigateTo({
            url: '../../coupon/couponDetails/couponDetails?couponActivityId=' + pageInfo.couponActivityId + '&type=assign&isExternal=false'
          })
        } else {
          wx.showToast({
            title: '您还不是会员，请绑定手机号成为会员~',
            icon: 'none',
            duration: 2000
          })
          setTimeout(() => {
            that.handlePopupPhone()
          }, 2000);
        }
      }
    } else if (pageInfo.linkType === 'URL') {
      // 链接
      let url = null
      if (pageType === 'activity') {
        url = pageInfo.linkUrl
      } else if (pageType === 'banner') {
        url = pageInfo.link
      }
      var index = '?'
      let webUrl = url
      if (url.indexOf(index) > -1) {
        webUrl = webUrl + '&storeId=' + this.data.storeId + '&type=normal'
      }
      let urlData = {
        url: encodeURIComponent(webUrl)
      }
      console.log(webUrl, urlData)
      let jsonUrl = JSON.stringify(urlData)
      wx.navigateTo({
        url: '../../advertising/advertising?webUrl=' + jsonUrl
      })
    } else {

    }
  },
  // 获取积分商城商品
  getScoreProduct: function (storeId) {
    const that = this
    let page = 1
    let pageSize = 0
    let business = 'SCORE'
    let postData = {
      page: page,
      pageSize: pageSize,
      storeIdEquals: storeId,
      business: business
    }
    productService.query(postData).then(res => {
      console.log(res)
      if (res.records && res.records.length > 0) {
        let tempList = []
        res.records.forEach(item => {
          let produtlabel = []
          let promotions = []
          if (item.labels && item.labels.length > 0) {
            item.labels.forEach(ele => {
              if (ele.type === 'GOODSLABEL') {
                produtlabel.push(ele)
              } else if (ele.type === 'PROMOTIONLABEL') {
                promotions.push(ele)
              }
            })
          }
          let tempItem = {
            ...item,
            produtlabel: produtlabel,
            promotions: promotions
          }
          tempList.push(tempItem)
        })
        let newTempList = that.productsSort(tempList)
        that.setData({
          goodsList: newTempList
        })
      }
    })
  },
  // 商品排序
  productsSort: function (array) {
    let balanceArray = []
    let allArray = []
    array.forEach(ele => {
      if (ele.balance === 0) {
        balanceArray.push(ele)
      } else {
        allArray.push(ele)
      }
    });
    const tempArray = allArray.concat(balanceArray)
    return tempArray
  },
  // 获取个人积分数据
  getMemberScore: function () {
    const that = this
    if (app.globalData.userInfo.member) {
      this.setData({
        member: app.globalData.userInfo.member,
        isMember: true
      })
      memberService.getBalance(that.data.member.mobile).then(res => {
        console.log(res)
        that.setData({
          score: res
        })
      }).catch(e => {
        wx.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000
        })
      })
    } else {

    }
  },
  // 跳转到商品详情页面
  toGoodsDetail: function (val) {
    wx.navigateTo({
      url: '../../goods/goodsDetail/goodsDetail?productId=' + val.currentTarget.dataset.goodsid + '&storeId=' + this.data.storeId + '&type=score'
    })
  },
  // 查看兑换记录
  toScoreOrder: function () {
    wx.navigateTo({
      url: '../scoreOrder/scoreOrder'
    })
  },
  // 前往下单
  toPerfectOrder: function (val) {
    const that = this
    const goodsList = that.data.goodsList
    var good = null
    goodsList.forEach(item => {
      if (item.id === val.currentTarget.dataset.goodsid) {
        good = item
      }
    })
    if (good.balance > 0) {
      if (that.data.score > good.exchangeScores) {
        try {
          let scoreMall = {
            allPrice: good.sellPrice,
            storeId: this.data.storeId,
            goodsList: [],
            orderType: 'scoreMall',
            score: good.exchangeScores
          }
          let tempData = {
            ...good,
            productId: good.id,
            productNum: 1,
            sellPrice: good.sellPrice,
          }
          scoreMall.goodsList.push(tempData)
          console.log(scoreMall)
          wx.setStorageSync('wj_shopcart', scoreMall)
        } catch (e) {
          console.log(e)
        }
        // 判断是否绑定手机号
        if (app.globalData.userInfo.member) {
          wx.navigateTo({
            url: '../../order/perfectOrder/perfectOrder'
          })
        } else {
          that.handlePopupPhone()
        }
      } else {
        wx.showToast({
          title: '积分不足',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      wx.showToast({
        title: '您来晚了，商品已售空',
        icon: 'none',
        duration: 2000
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const self = this
    // 判断globalData.storeInfo有没有数据，有数据，则使用选择的门店数据，没有，则根据当前地理位置获取最近门店
    if (app.globalData.storeInfo) {
      self.setData({
        storeId: app.globalData.storeInfo.id,
        storeName: app.globalData.storeInfo.name
      })
      this.getScoreProduct(app.globalData.storeInfo.id)
      this.getBannerList(app.globalData.storeInfo.id)
    } else {
      // 获取当前地理位置，然后筛选出最近的门店，根据当前门店获取门店的商品
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude
          var longitude = res.longitude
          var speed = res.speed
          var accuracy = res.accuracy
          try {
            var tempAllStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
            if (tempAllStores) {
              // Do something with return value
              let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
              app.globalData.storeInfo = tempAllStores[tempIndex];
              // 获取当前门店的所有分类和商品
              self.getScoreProduct(tempAllStores[tempIndex].id)
              self.getBannerList(tempAllStores[tempIndex].id)
            } else {
              // 查询所有门店
              storeService.queryList().then(res => {
                var allStores = res;
                try {
                  wx.setStorageSync('wj_allStores', allStores)
                } catch (e) {
                  console.log(e)
                }
                let tempIndex = self.getNearestStore(allStores, latitude, longitude);
                return allStores[tempIndex]
              }).then(res => {
                app.globalData.storeInfo = res;
                self.getScoreProduct(res.id)
                self.getBannerList(res.id)
              })
            }
          } catch (e) {
            console.log(e)
            // Do something when catch error
          }
        },
        fail: function (err) {
          console.log(err)
        }
      })
    }
    this.getMemberScore()
    if (self.options.mobile && self.options.mobile != '' && self.options.mobile != undefined) {
      const mobile = self.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },
  /**
   * 获取banner图片
   */
  getBannerList: function (storeId) {
    if (storeId) {
      bannerService.getStoreBannerList('SCOREMALL', storeId).then(res => {
        console.log(res)
        this.setData({
          banners: res
        })
      })
    } else {
      bannerService.getBannerList('SCOREMALL').then(res => {
        console.log(res)
        this.setData({
          banners: res
        })
      })
    }

  },
  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      storeName: allStores[tempIndex].name,
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.phone === true) {
      this.handlePopupPhone()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/score/scoreMall/scoreMall?mobile=' + memberId,
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {}
      }
    } else {
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/score/scoreMall/scoreMall',
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {}
      }
    }
  },

  /**
   * 获取banner图片
   */
  getBannerList: function (storeId) {
    bannerService.getStoreBannerList('SCOREMALL', storeId).then(res => {
      console.log(res)
      this.setData({
        banners: res
      })
    })
    // 获取banner图片
    // bannerService.getBannerList('SCOREMALL').then(res => {
    //   console.log(res)
    //   this.setData({
    //     banners: res
    //   })
    // })
  },
  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
      } else {
        self.setData({
          userInfo: user.wxaUser,
          hasUserInfo: true,
        })
      }
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false
      })
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})